<?php
defined('IN_IA') or exit('Access Denied');


class rising {


    protected $graphic = 'www.ezhjx.cn';


    protected $send = array(
        'www.paoge520.cn',
        'xx.cqxygzs.cn',
        'www.small_program.com',

    );


    protected $chason = 'client.chason.vip';


    protected $double = 'hao.weixue.mobi';

    public $error;


    protected $popularity = 'wx.tatakj.cn';


    public function isQqhome()
    {
        global  $_W;
        $basename = pathinfo($_W['siteroot']);
        return 'diancan.wmmob.cn' == $basename['basename'];
    }


    public function isPopularitye()
    {
        global  $_W;
        $basename = pathinfo($_W['siteroot']);
        return $this->popularity == $basename['basename'];
    }


    public function isDouble()
    {
        global  $_W;
        $basename = pathinfo($_W['siteroot']);
        return $this->double == $basename['basename'];
    }


    public function isOpenDouble()
    {
        return $this->isDouble() && getConfig('is_double') == 2;
    }


    public function isGraphic()
    {
        return true;
        global  $_W;
        $basename = pathinfo($_W['siteroot']);
        return $this->graphic == $basename['basename'];
    }


    public function isChason()
    {
        global  $_W;
        $basename = pathinfo($_W['siteroot']);
        return $this->chason == $basename['basename'];
    }

    public function isSend()
    {
        global  $_W;
        $basename = pathinfo($_W['siteroot']);
        if (in_array($basename['basename'], $this->send)) {
            return true;
        }
        return false;
    }
    /**
     * @param $member_id
     * @param $currency
     * @param int $type
     * @param string $remarks
     * @return bool
     */
    public function change_currency($member_id, $currency, $type = 1, $remarks = '')
    {
        if ($currency <= 0) {
            return true;
        }
        $currency_name = getConfig('currency_name', '金币');
        $member = p_get('member', array('id' => $member_id));
        if (empty($member)) {
            return true;
        }
        if (in_array($type, array(1, 2, 3, 4, 7))) {
            $after_currency = $member['currency'] + $currency;
            $task_bonus = getConfig('task_bonus', 1);

            if ($type != 4 && $type != 7) {
                if (!$this->update_day($member_id, $currency, $type)) {
                    $this->error = $currency_name . '更新失败';
                    return false;
                }
            }

            if ($type == 7 && $task_bonus == 2) {
                if (!$this->update_day($member_id, $currency, $type)) {
                    $this->error = $currency_name . '更新失败';
                    return false;
                }
            }

        } else {
            if ($member['currency'] < $currency) {
                $this->error = $currency_name . '不足';
                return false;
            }
            $after_currency = $member['currency'] - $currency;
        }

        $update = array('currency' => $after_currency);
        if (!p_update('member', $update, array('id' => $member_id))) {
            $this->error = $currency_name . '变更失败';
            return false;
        }

        $currency_log = array(
            'member_id' => $member_id,
            'currency' => $currency,
            'type' => $type,
            'same_day' => strtotime(date('Y-m-d')),
            'created' => time()
        );
        if ($remarks) {
            $currency_log['remarks'] = $remarks;
        }
        if (p_insert('currency_log', $currency_log)) {
            return true;
        }

        $this->error = '日志更新出错';
        return false;
    }


    /**
     * 更新当天
     * @param $member_id
     * @param $currency
     * @return bool
     */
    public function update_day($member_id, $currency, $type = 1)
    {
        $same_day = strtotime(date('Y-m-d'));
        $day = p_get('day', array('member_id' => $member_id, 'same_day' => $same_day));
        if (empty($day)) {
            $insert = array(
                'member_id' => $member_id,
                'same_day' => $same_day,
                'currency' => $currency,
                'updated' => time(),
                'created' => time(),
            );
            if ($type == 1) {
                $insert['clock'] = 1;
            }
            return p_insert('day', $insert);
        }
        $u = array(
            'currency' => $day['currency'] + $currency,
            'updated' => time()
        );
        if ($type == 1) {
            $u['clock'] = $day['clock'] + 1;
        }
        return p_update('day', $u, array('id' => $day['id']));
    }


    /**
     * @param $member_id
     * @return array|bool
     */
    public function get_clock_today($member_id)
    {
        $same_day = strtotime(date('Y-m-d'));
        $day = p_get('day', array('member_id' => $member_id, 'same_day' => $same_day));
        if (empty($day)) {
            $day = array(
                'member_id' => $member_id,
                'same_day' => $same_day,
                'clock' => 0,
                'currency' => 0,
                'updated' => time(),
                'created' => time(),
            );
            p_insert('day', $day);
        }
        $day['currency'] = floatval($day['currency']);
        return $day;
    }




    /**
     * 资金变动
     *
     * @param $member_id
     * @param $money
     * @param int $type
     * @return bool
     */
    public function change_money($member_id, $money, $type = 1)
    {
        if ($money <= 0) {
            return true;
        }
        $member = p_get('member', array('id' => $member_id));
        if (in_array($type, array(1, 3, 4))) {
            $after_money = $member['money'] + $money;
        } else {

            if (intval($member['money'] * 100) < intval($money * 100)) {
                $this->error = '余额不足';
                return false;
            }
            $after_money = (intval($member['money'] * 100) - intval($money * 100)) / 100;
        }

        $update = array('money' => $after_money);
        if (!p_update('member', $update, array('id' => $member_id))) {
            $this->error = '余额变动失败';
            return false;
        }

        $money_log = array(
            'member_id' => $member_id,
            'money' => $money,
            'type' => $type,
            'after_money' => $after_money,
            'created' => time()
        );

        if (p_insert('money_log', $money_log)) {
            return true;
        }

        $this->error = '日志更新出错';
        return false;
    }




    /**
     * 更新员工
     * @param $member_id
     * @param $downline_id
     * @param int $type
     * @param int $is_auth
     * @return bool
     */
    public function update_group($member_id, $downline_id, $type = 1, $is_auth = 1)
    {
        pdo_begin();
        try{
            $one_member = p_get('member', array('id' => $member_id));
            if (empty($one_member)) {
                return true;
            }

            $one = array(
                'member_id' => $member_id,
                'downline_id' => $downline_id,
                'level' => 1,
                'updated' => time(),
                'created' => time()
            );

            if (!p_insert('group', $one)) {
                throw new Exception('更新失败');
            }

            $two_member = p_get('member', array('id' => $one_member['parent_id']));

            if (empty($two_member) || $type != 1) {
                pdo_commit();
                return true;
            }
            $two = array(
                'member_id' => $two_member['id'],
                'downline_id' => $downline_id,
                'level' => 2,
                'updated' => time(),
                'created' => time()
            );
            if (!p_insert('group', $two)) {
                throw new Exception('更新失败');
            }

            pdo_commit();
        } catch (Exception $e) {
            $this->error = $e->getMessage();
            pdo_rollback();
            return false;
        }
        return true;
    }






    /**
     * 用户活力币记录
     * @param $member_id
     * @param $p
     * @param int $page_size
     * @return array
     */
    public function currency_log($member_id, $p, $page_size = 10)
    {
        $limit = ($p - 1) * $page_size;
        $log = p_getall('currency_log', array('member_id' => $member_id), array(),'', array('id desc'), "{$limit}, {$page_size}");

        if ($log) {
            $types = array(
                1 => '兑换商品',
                2 => '自己生产',
                3 => '好友进贡',
                4 => '签到奖励',
                5 => '唤醒好友',
                6 => '完成任务',
                7 => '签到翻倍',
            );
            foreach ($log as & $value) {
                $value['remarks'] = $types[$value['type']];
                $value['mold'] = in_array($value['type'], array(2, 3, 4, 5, 6, 7)) ? 1 : 2;
                $value['createTime'] = date('Y.m.d', $value['created']);
            }
        }

        return $log;
    }


    /**
     * @param $money
     * @param string $member_id
     * @return bool
     */
    public function cash($money, $member_id = '')
    {
        $member = p_get('member', array('id' => $member_id));

        $MerchPay = new MerchPay();
        $trade_no = date("YmdHis", time()) . $member['id'] . rand(100, 999);
        $res = $MerchPay->pay($member['openid'], $trade_no, $money, ('来自'. getConfig('xcx_title') .'小程序提现'), '');//本机ip

        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {

            return true;
        }
        if ($_GET['dd']) {
            var_dump($res);
        }
        $this->error = isset($res[0]) ? $res[0] : '提现失败';
        return false;
    }


    /**
     *
     * @param $member_id
     * @param $fee_type
     * @param $memo
     * @param $cash_id
     * @return bool
     */
    public function qqCash($member_id, $fee_type, $memo = '', $cash_id = '')
    {
        $member = p_get('member', array('id' => $member_id));
        if (empty($memo)) {
            $memo = '(来自'. getConfig('xcx_title') .'小程序提现)';
        }
        $out_trade_no = date("YmdHis", time()) . $member['id'] . rand(100, 999);
        $data = array(
            'input_charset' => 'UTF-8',
            'openid'        => $member['openid'],
            'uin'           => $member['qq'],
            'mch_id'        => getConfig('qq_mch_id'),
            'nonce_str'     => $out_trade_no,
            'out_trade_no'  => $cash_id.substr($out_trade_no, 0 , 9),
            'fee_type'      => "CNY",
            'total_fee'     => (int)($fee_type * 100),
            'memo'          => $memo,
            'op_user_id'    => getConfig('op_user_id'),
            'op_user_passwd'=> md5(getConfig('op_user_passwd')),
            'spbill_create_ip' => CLIENT_IP,
        );
        $data['sign'] = qqAutograph($data);
        $s = $this->curl_post_ssl('https://api.qpay.qq.com/cgi-bin/epay/qpay_epay_b2c.cgi', $data);

        $result = json_decode(json_encode(simplexml_load_string($s, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
            return true ;
        }

        $this->error = $result['err_code'] ;
        //$this->error = $result['err_code_desc'];
        return false;

    }


    /**
     * 企业付款发起请求
     * 此函数来自:https://pay.weixin.qq.com/wiki/doc/api/download/cert.zip
     */
    public function curl_post_ssl($url, $xmldata, $second = 30, $aHeader = array()) {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //以下两种方式需选择一种
        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, getConfig('qq_apiclient_cert'));
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, getConfig('qq_apiclient_key'));

        //第二种方式，两个文件合成一个.pem文件
        //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');

        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            //echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }


    /**
     * 生成支付订单
     * @param $member_id
     * @param $money
     * @param $relation_id
     * @param int $type
     * @return bool|string
     */
    public function unifiedOrder($member_id, $money, $relation_id, $type = 1)
    {
        $trade_no = date("YmdHis", time()) . $member_id . mt_rand(10000, 99999);
        $pay = array(
            'member_id' => $member_id,
            'trade_no' => $trade_no,
            'money' => $money,
            'relation_id' => $relation_id,
            'type' => $type,
            'crested' => time()
        );

        if (p_insert('pay_order', $pay)) {
            return $trade_no;
        }
        return false;
    }


    /**
     *  随机字符串
     */
    public function out_trade_no()
    {
        $date = date('Ymd');
        $rand = substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))),0,12);
        return $date . $rand . $this->getIssueNumber(12);
    }


    /**
     * @param $length
     * @return string
     */
    protected function getIssueNumber($length)
    {
        $str ='201812345678ab998c76541d230e7899a638k527d411236987412';
        $len =strlen($str)-1;
        $randStr='';
        for($i=0;$i<$length;$i++){
            $num=mt_rand(0,$len);
            $randStr .= $str[$num];
        }
        return $randStr;
    }



    /**
     * @param $member_id
     * @param $code
     * @return bool
     */
    public function checkcaptcha($member_id, $code)
    {
        if (empty($code)) {
            $this->error = '请填写验证码';
            return false;
        }
        global $_W;

        $codehash = md5(strtolower($code) . $_W['config']['setting']['authkey']);
        $res = p_get('code', array('member_id' => $member_id));
        if (empty($res) || ($res['created'] - time()) > 800) {
            p_delete('code', array('id' => $res['id']));
            $this->error = '验证码已经过期';
            return false;
        }
        if ($codehash != $res['code']) {
            $this->error = '验证码错误';
            return false;
        }
        p_delete('code', array('id' => $res['id']));

        return true;
    }


    /**
     * @param $member_id
     * @param $popularity
     * @param int $type
     * @param string $remarks
     * @return bool
     */
    public function change_popularity($member_id, $popularity, $type = 1, $remarks = '')
    {
        if ($popularity <= 0) {
            return true;
        }
        $currency_name = '人气值';
        $member = p_get('member', array('id' => $member_id));
        if (empty($member)) {
            return true;
        }
        if (in_array($type, array(1))) {
            $after_currency = $member['popularity'] + $popularity;


        } else {
            if ($member['popularity'] < $popularity) {
                $this->error = $currency_name . '不足';
                return false;
            }
            $after_currency = $member['popularity'] - $popularity;
        }

        $update = array('popularity' => $after_currency);
        if (!p_update('member', $update, array('id' => $member_id))) {
            $this->error = $currency_name . '变更失败';
            return false;
        }

        $currency_log = array(
            'member_id' => $member_id,
            'popularity' => $popularity,
            'type' => $type,
            'same_day' => strtotime(date('Y-m-d')),
            'created' => time()
        );
        if ($remarks) {
            $currency_log['remarks'] = $remarks;
        }
        if (p_insert('popularity_log', $currency_log)) {
            return true;
        }

        $this->error = '日志更新出错';
        return false;
    }



    /**
     * 获取广告
     * @param $position
     * @param array $limit
     * @return array|mixed
     */
    public function getAdvertisement($position, $limit = array())
    {
        if (!in_array($position, array(1))) {
            return ad(p_get('advertisement', array('position' => $position, 'status' => 1)));
        } else {
            $ad = p_getall('advertisement', array('position' => $position, 'status' => 1), array(), '', array('sort desc'), $limit);

            return empty($ad) ? array() : array_map('ad', $ad);
        }
    }


    /**
     * 打卡时间段
     * @return bool
     */
    public function is_time_slot()
    {
        $h = date('H');
        if (empty(p_get('time_slot', array()))) {
            return true;
        }

        $sql = "SELECT * FROM " . prefix('time_slot') . " WHERE {$h} >= start AND `end` >= {$h} " . get_uniacid();

        return pdo_fetch($sql);
    }



    /**
     * @param $member_id
     * @return array
     */
    public function subsection($member_id)
    {
        $h = date('H');
        $sql = "SELECT * FROM" . prefix('subsection') . " WHERE start_time <= {$h} AND end_time > {$h}" . get_uniacid();
        $current = p_fetch($sql);
        $date = date('Y-m-d');
        if ($current) {
            $same_day = strtotime($date);

            $start = strtotime(($date . ' ' . $current['start_time'] . ':00:00'));
            $end = strtotime(($date . ' ' . $current['end_time'] . ':00:00'));

            $sql = "SELECT * FROM" . prefix('member_clock') . " WHERE member_id={$member_id} AND same_day={$same_day} AND created > {$start} AND created < {$end}";

            if (!$participate = p_fetch($sql)) {
                return array(
                    'state' => 1, // 可以打卡
                    'subsection' => $current
                );
            }
        }

        if ($current) {
            $sql = "SELECT * FROM" . prefix('subsection') . " WHERE start_time > {$current['end_time']} " . get_uniacid() . " ORDER BY end_time ASC";
        } else {
            $sql = "SELECT * FROM" . prefix('subsection') . " WHERE start_time > {$h} " . get_uniacid() . " ORDER BY end_time ASC";
        }

        $subsection = p_fetch($sql);
        if ($subsection) {
            $subsection['surplus'] = strtotime($date . ' ' . $subsection['start_time'] . ':00:00') - time();
            return array(
                'state' => 2, // 下次打卡
                'subsection' => $subsection
            );
        }
        return array(
            'state' => 3 // 今日打卡任务已经完成
        );
    }



    public function get_ad_type($type)
    {
        $types = array(
            1 => 'grid',
            2 => '',
            3 => 'video',
        );
        return $types[$type];
    }
}